<?php


namespace app\api\controller;


use app\admin\model\ShopFinanceDay;
use app\admin\model\UserOrder;
use app\admin\service\Hnnx;
use think\db\Query;
use think\facade\Db;
use think\facade\Log;

class Pay extends Api
{

    /**
     * @title 支付回调
     * @author FashionJune
     */
    public function payNotify()
    {
        //根据回调结果更新订单状态
        $before_data = file_get_contents('php://input');
        parse_str($before_data, $data);
        Log::write(json_encode($data), 'pay-notify');
        $return = Hnnx::instance()->notify($data);

        if ($return == 1) {//验签通过，根据结果修改订单状态
            $row = UserOrder::where('order_sn', $data['MerSeqNo'])->find();
            if (!$row || $row->status > 1) {
                return 'ok';
            }
//            $update_data = [
//                'epay_order_sn' => $data['TransSeqNo'],
//                'terminal_id' => $data['TermId'],
//                'trans_date' => $data['MerDateTime'],
//                'pay_time' => strtotime($data['MerDateTime']),
//                'actual_pay' => $data['TransAmt'],
//                'status' => 2,
//            ];
            $row->epay_order_sn = $data['TransSeqNo'];
            $row->terminal_id = $data['TermId'];
            $row->trans_date = $data['MerDateTime'];
            $row->pay_time = strtotime($data['MerDateTime']);
            $row->actual_pay = $data['TransAmt'];
            $row->status = 2;
            Db::starttrans();
            try {
                $row->save();
                UserOrder::init()->insertApart($row->toArray());
                //商家和系统统计收入
                $update_finance = [
                    'store_id' => $row['store_id'],
                    'price_total' => $row['total_price'],
                    'cashcard_total' => $row['cashcard_dec'],
                    'date' => strtotime('today')
                ];
                ShopFinanceDay::init()->updateFinance($update_finance);
            } catch (\Exception $e) {
                Db::rollback();
                Log::write($e->getMessage() . "[{$row->order_sn}]");
//                echo $e->getMessage();
            }
            Db::commit();
        }
        return 'success';
    }


    /**
     * @title 批量获取未支付状态订单的支付结果
     * @author FashionJune
     */
    public function getPayResult()
    {
        $map = [
            ['status', '=', 1],
            ['query_times', '<', 3]
        ];
        $order_list = UserOrder::where($map)->order('id', 'desc')->column('query_times', 'order_sn');
        try {
            foreach ($order_list as $order_sn => $query_times) {
                $query_times++;
                $re = Hnnx::instance()->qryQrOrderStatus($order_sn);
//                [
//                    "code" => 1
//                      "msg" => "交易成功"
//                      "data" => array:5 [
//                                        "InnerFundTransNbr" => "000013473911"
//                        "TransSeqNbr" => "202104020020283508"
//                        "TransStatus" => "0"
//                        "PayTypCd" => "C"
//                        "Addr" => "11.1.197.17:20881"
//                      ]
//                ]
//                if ($re['code'] !== 1) {
//                    trace(json_encode($re));
//                }
                $trans_status = (int)$re['data']['TransStatus'];//交易结果
                if (isset($trans_status) && $trans_status == 0) {//交易成功
                    $update_data = [
                        'epay_order_sn' => $re['data']['TransSeqNbr'],
//                        'terminal_id' => $re['data']['TermId'],
                        'trans_date' => substr($re['data']['TransSeqNbr'], 0, 8),
                        'pay_time' => strtotime($re['data']['TransSeqNbr']),
                        'status' => 2,
                    ];
                    $update_data['pay_time'] = strtotime($update_data['trans_date']);
                } elseif ($query_times > 3 || $trans_status === 1 || $trans_status === 2 || $trans_status === 9) {
                    //多次查询失败|交易失败|撤销|交易超时
                    $update_data = ['status' => -1, 'query_times' => $query_times];
                } elseif ($trans_status === 3 || $trans_status === 4) {//部分退款|全部退款
                    $update_data = ['status' => 4, 'query_times' => $query_times];
                } else {
                    continue;
                }
                Db::startTrans();
                try {
                    $row = UserOrder::where('order_sn', $order_sn)->find();
                    foreach ($update_data as $k => $v) {
                        $row->$k = $v;
                    }
                    $row->save();
                    UserOrder::init()->insertApart($row->toArray());
                    //商家和系统统计收入
                    $update_finance = [
                        'store_id' => $row['store_id'],
                        'price_total' => $row['total_price'],
                        'cashcard_total' => $row['cashcard_dec'],
                        'date' => strtotime('today')
                    ];
                    ShopFinanceDay::init()->updateFinance($update_finance);
                } catch (\Exception $e) {
                    Db::rollBack();
                    api_error('DB_error:' . $e->getMessage());
                }
                Db::commit();

            }
        } catch (\Exception $e) {
           api_error($e->getMessage());
        }
        api_success('订单状态已更新');
    }

    /**
     * @title 退款(全额)
     * @author FashionJune
     */
    public function refund()
    {
        //TODO 退款要先根据订单号获取年月来对分表进行修改
        $order_id = input('order_id') ?? api_error('未找到订单');
        $order = UserOrder::with(['store' => function ($query) {
            $query->field(['id', 'merchant_id']);
        }])->find($order_id);
        (!$order) && api_error('未找到订单记录');
        if ($order['status'] != 2) {
            api_error('仅付款成功订单可以进行退款操作');
        } /*elseif ($order['uid'] != $this->user['user_id']) {
            api_error('非本人订单禁止操作');
        }*/
        $refund_data  = [
            'OrigMerSeqNbr' => $order['order_sn'],
            'OrigMerDate' => $order['trans_date'],
            'SubMerchantId' => $order['store']['merchant_id'],
            'OrigTransAmt' => $order['true_price'],
        ];
//        dd($refund_data);
        $re = Hnnx::instance()->tuikuan($refund_data);
//        {
//            "code": 1,
//            "msg": "交易成功",
//            "data": {
//                    "TransSeqNbr": "202104020020283522",
//                "TransStatus": "5",
//                "PayTypCd": "C",
//                "Addr": "11.1.197.17:20881"
//            }
//        }
        if ($re['code'] == 1) {
            UserOrder::init()->afterRefund($order_id);
        }
    }

    /**
     * @title 支付成功展示页
     * @author FashionJune
     * @return mixed
     */
    public function pay_success()
    {
        return $this->fetch('index/pay_success');
    }


}